package com.ttbj.timer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import com.ttbj.order.dao.OrderMapper;
import com.ttbj.order.po.Order;
import com.ttbj.timer.cache.AchievedRedisService;
import com.ttbj.timer.po.AchievedOrder;
import com.ttbj.timer.service.achieved.AchievedService;
import com.ttbj.timer.service.achieved.OnAchieveListener;

@Service
public class TimerStartupListener implements ApplicationListener<ContextRefreshedEvent> {

	private static final Logger log = LoggerFactory.getLogger(TimerStartupListener.class);

	@Autowired
	ThreadPoolTaskExecutor taskExecutor = null;

	@Autowired
	AchievedService achievedService = null;

	@Autowired
	OrderMapper orderMapper = null;
	
	@Autowired
	AchievedRedisService achievedRedisService = null;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent evt) { // 启动监听
		log.error(">>>>>>>>>>>>系统启动完成，启调onApplicationEvent()");
		if (evt.getApplicationContext().getParent() == null) {
			return;
		}
		
		taskExecutor.execute(() -> {
			log.error("查找需要入队的订单");
			achievedService.convertQueue();

		});
		
		achievedService.start(new OnAchieveListener() {
			@Override
			public void onDelayedAchieve(AchievedOrder order) {
				taskExecutor.execute(() -> { // 完成监听实现
					log.info("监听开始执行订单----"+ order);
					Long orderId = order.getOrderId();
					Order od = new Order(orderId);
					od.setOrderState(6);
					orderMapper.updateByPrimaryKeySelective(od);
					achievedRedisService.delElement(orderId);
				});
			}
		});

		

	}

}
